package com.tianji.remark.service.impl;


import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;


import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;


/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author Aimer
 * @since 2025-11-14
 */
@Service
@RequiredArgsConstructor
public class LikedRecordRedisServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper rabbitMqHelper;
    private final StringRedisTemplate redisTemplate;
    @Override
    public void addLikeRecord(LikeRecordFormDTO likeRecordFormDTO) {
        // 判断是新增点赞还是取消点赞
        boolean success = likeRecordFormDTO.getLiked() ? like(likeRecordFormDTO) : unlike(likeRecordFormDTO);
        // 判断是否成功失败直接结束
        if (!success){
            return;
        }
        // 统计点赞的这个业务点赞总数
        Long count = redisTemplate.opsForSet().size(RedisConstants.LIKE_BIZ_KEY_PREFIX + likeRecordFormDTO.getBizId());
        if (count == null){
            return;
        }
        // 存入到zset缓存中
        redisTemplate.opsForZSet().add(RedisConstants.LIKES_TIMES_KEY_PREFIX+likeRecordFormDTO.getBizType(),likeRecordFormDTO.getBizId().toString(),count);
    }

    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        // 获取登录用户id
        Long userId = UserContext.getUser();
        // 查询点赞状态
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });

        // 返回结果
        Set<Long> set = new HashSet<>();
        for (int i = 0; i < objects.size(); i++) {
            Boolean o = (Boolean) objects.get(i);
            if (o){
                set.add(bizIds.get(i));
            }
        }
        return set;
    }

    @Override
    public void readLikedTimesAndSendMessage(String bizType,Integer max) {
        // 1.读取并移除Redis中缓存的点赞总数
        String key = RedisConstants.LIKES_TIMES_KEY_PREFIX + bizType;
        Set<ZSetOperations.TypedTuple<String>> tuples = redisTemplate.opsForZSet().popMin(key, max);
        if (CollUtils.isEmpty(tuples)){
            return;
        }
        // 数据转换
        List<LikedTimesDTO> list = new ArrayList<>();
        for (ZSetOperations.TypedTuple<String> tuple : tuples) {
            LikedTimesDTO likedTimesDTO = new LikedTimesDTO();
            if (tuple.getScore() == null || tuple.getValue() == null){
                continue;
            }
            likedTimesDTO.setBizId(Long.valueOf(tuple.getValue()));
            likedTimesDTO.setLikedTimes(tuple.getScore().intValue());
            list.add(likedTimesDTO);
        }
        // 发送mq通知
        rabbitMqHelper.send(
                LIKE_RECORD_EXCHANGE,
                StringUtils.format(LIKED_TIMES_KEY_TEMPLATE, bizType),
                list);
    }

    private boolean unlike(LikeRecordFormDTO likeRecordFormDTO) {
        // 获取当前登录用户id
        Long userId = UserContext.getUser();
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + likeRecordFormDTO.getBizId();
        Long remove = redisTemplate.opsForSet().remove(key, userId);
        return remove != null && remove > 0;
    }

    private boolean like(LikeRecordFormDTO likeRecordFormDTO) {
        // 获取当前登录用户id
        Long userId = UserContext.getUser();
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + likeRecordFormDTO.getBizId();
        Long result = redisTemplate.opsForSet().add(key, userId.toString());
        return result != null && result > 0;
    }
}
